package com.example.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.bean.Order;
import com.example.bean.OrderItem;
import com.example.bean.Product;
import com.example.bean.User;
import com.example.order.mapper.OrderItemMapper;
import com.example.order.mapper.OrderMapper;
import com.example.order.service.OrderService;
import com.example.params.OrderParams;
import com.example.shoputils.constants.HttpCode;
import com.example.shoputils.resp.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @Author 刘武贵
 * @Date 2024-03-02 23:10
 * @Description 功能描述：订单接口实现类（使用Ribbon实现负载均衡）
 */
@Slf4j
@Service("orderServiceV4")
public class OrderServiceV4Impl implements OrderService {

    /**
     * 订单Mapper
     */
    @Resource
    private OrderMapper orderMapper;

    /**
     * 订单条目Mapper
     */
    @Resource
    private OrderItemMapper orderItemMapper;

    /**
     * RestTemplate对象，用于发送HTTP请求
     */
    @Resource
    private RestTemplate restTemplate;

    /**
     * 用户服务器地址
     * userServer的值需要与用户微服务下的application.yml（shop-user/src/main/resources/application.yml）文件中的如下配置的值相同。
     */
    private String userServer = "server-user";

    /**
     * 产品服务器地址
     * productServer的值需要与商品微服务下的application.yml（shop-product/src/main/resources/application.yml）文件中的如下配置的值相同。
     */
    private String productServer = "server-product";

    /**
     * 保存订单
     * @param orderParams 订单参数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrder(OrderParams orderParams) {
        if (orderParams.isEmpty()){
            throw new RuntimeException("参数异常: " + JSONObject.toJSONString(orderParams));
        }

        User user = restTemplate.getForObject("http://" + userServer + "/user/get/" + orderParams.getUserId(), User.class);
        if (user == null){
            throw new RuntimeException("未获取到用户信息: " + JSONObject.toJSONString(orderParams));
        }

        // 获取商品信息
        Product product = restTemplate.getForObject("http://" + productServer + "/product/get/" + orderParams.getProductId(), Product.class);
        if (product == null){
            throw new RuntimeException("未获取到商品信息: " + JSONObject.toJSONString(orderParams));
        }

        // 检查商品库存是否充足
        if (product.getProStock() < orderParams.getCount()){
            throw new RuntimeException("商品库存不足: " + JSONObject.toJSONString(orderParams));
        }

        // 创建订单对象
        Order order = new Order();
        order.setAddress(user.getAddress());
        order.setPhone(user.getPhone());
        order.setUserId(user.getId());
        order.setUsername(user.getUsername());
        order.setTotalPrice(product.getProPrice().multiply(BigDecimal.valueOf(orderParams.getCount())));

        // 保存订单到数据库
        orderMapper.insert(order);

        // 创建订单项对象
        OrderItem orderItem = new OrderItem();
        orderItem.setNumber(orderParams.getCount());
        orderItem.setOrderId(order.getId());
        orderItem.setProId(product.getId());
        orderItem.setProName(product.getProName());
        orderItem.setProPrice(product.getProPrice());

        // 保存订单项到数据库
        orderItemMapper.insert(orderItem);

        // 扣减商品库存
        Result<Integer> result = restTemplate.getForObject("http://" + productServer + "/product/update_count/" + orderParams.getProductId() + "/" + orderParams.getCount(), Result.class);
        if (result.getCode() != HttpCode.SUCCESS){
            throw new RuntimeException("库存扣减失败");
        }

        log.info("库存扣减成功");
    }
}
